// API配置
const API_BASE = 'http://localhost:8000/api';

// 全局变量
let images = [];
let selectedImages = new Set();

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    loadDownloadHistory();
    // 默认搜索
    searchImages();
});

// 搜索图片
async function searchImages() {
    const keyword = document.getElementById('keyword').value || '小诺机器人';
    const limit = document.getElementById('limit').value;
    const resolution = document.getElementById('resolution').value;
    const format = document.getElementById('format').value;

    showLoading(true);
    
    try {
        const response = await fetch(`${API_BASE}/search`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                keyword,
                limit: parseInt(limit),
                resolution,
                format
            })
        });

        const result = await response.json();
        
        if (result.success) {
            images = result.data;
            displayImages();
            updateStats();
        }
    } catch (error) {
        console.error('搜索失败:', error);
        alert('搜索失败，请检查网络连接');
    } finally {
        showLoading(false);
    }
}

// 显示图片
function displayImages() {
    const container = document.getElementById('imageContainer');
    const emptyState = document.getElementById('emptyState');
    
    if (images.length === 0) {
        container.innerHTML = '';
        emptyState.style.display = 'block';
        return;
    }
    
    emptyState.style.display = 'none';
    container.innerHTML = '';
    
    images.forEach((image, index) => {
        const col = document.createElement('div');
        col.className = 'col-md-4 col-lg-3 mb-4';
        
        col.innerHTML = `
            <div class="card image-card" data-index="${index}" onclick="toggleSelect(${index})">
                <img src="${image.url}" class="card-img-top thumbnail" alt="${image.title}">
                <div class="card-body">
                    <h6 class="card-title">${image.title}</h6>
                    <p class="card-text">
                        <small class="text-muted">
                            <i class="fas fa-expand me-1"></i>${image.resolution}<br>
                            <i class="fas fa-file-image me-1"></i>${image.format.toUpperCase()}<br>
                            <i class="fas fa-weight me-1"></i>${image.size}
                        </small>
                    </p>
                </div>
                <div class="position-absolute top-0 end-0 m-2">
                    <input type="checkbox" class="form-check-input" id="check-${index}" 
                           onchange="event.stopPropagation()" onclick="event.stopPropagation()">
                </div>
            </div>
        `;
        
        container.appendChild(col);
    });
}

// 切换选择状态
function toggleSelect(index) {
    const checkbox = document.getElementById(`check-${index}`);
    const card = document.querySelector(`[data-index="${index}"]`);
    
    if (selectedImages.has(index)) {
        selectedImages.delete(index);
        card.classList.remove('selected');
        checkbox.checked = false;
    } else {
        selectedImages.add(index);
        card.classList.add('selected');
        checkbox.checked = true;
    }
    
    updateDownloadButton();
    updateStats();
}

// 清空选择
function clearSelection() {
    selectedImages.clear();
    document.querySelectorAll('.image-card').forEach(card => {
        card.classList.remove('selected');
    });
    document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
        checkbox.checked = false;
    });
    updateDownloadButton();
    updateStats();
}

// 更新下载按钮状态
function updateDownloadButton() {
    const downloadBtn = document.getElementById('downloadBtn');
    downloadBtn.disabled = selectedImages.size === 0;
}

// 更新统计信息
function updateStats() {
    document.getElementById('totalImages').textContent = images.length;
    document.getElementById('selectedImages').textContent = selectedImages.size;
    document.getElementById('statsCard').style.display = 'block';
}

// 显示/隐藏加载状态
function showLoading(show) {
    const loadingBar = document.getElementById('loadingBar');
    loadingBar.style.display = show ? 'block' : 'none';
}

// 下载选中的图片
async function downloadSelected() {
    if (selectedImages.size === 0) {
        alert('请先选择要下载的图片');
        return;
    }
    
    const selectedUrls = Array.from(selectedImages).map(index => images[index].url);
    
    showLoading(true);
    document.getElementById('loadingText').textContent = '正在打包下载...';
    
    try {
        const response = await fetch(`${API_BASE}/download`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                urls: selectedUrls
            })
        });

        const result = await response.json();
        
        if (result.success) {
            // 触发下载
            window.open(`${API_BASE}/download/${result.filename}`, '_blank');
            loadDownloadHistory();
            alert('下载已开始！');
        }
    } catch (error) {
        console.error('下载失败:', error);
        alert('下载失败，请重试');
    } finally {
        showLoading(false);
        document.getElementById('loadingText').textContent = '正在搜索...';
    }
}

// 加载下载历史
async function loadDownloadHistory() {
    try {
        const response = await fetch(`${API_BASE}/downloads`);
        const result = await response.json();
        
        if (result.success) {
            document.getElementById('downloadHistory').textContent = result.files.length;
            
            // 更新历史模态框
            const historyList = document.getElementById('historyList');
            if (result.files.length > 0) {
                historyList.innerHTML = result.files.map(file => `
                    <div class="d-flex justify-content-between align-items-center p-2 border-bottom">
                        <div>
                            <strong>${file.filename}</strong><br>
                            <small class="text-muted">${new Date(file.created).toLocaleString()}</small>
                        </div>
                        <a href="${API_BASE}/download/${file.filename}" class="btn btn-sm btn-primary">
                            <i class="fas fa-download"></i>
                        </a>
                    </div>
                `).join('');
            } else {
                historyList.innerHTML = '<p class="text-center text-muted">暂无下载历史</p>';
            }
        }
    } catch (error) {
        console.error('加载历史失败:', error);
    }
}

// 显示下载历史
function showHistory() {
    const modal = new bootstrap.Modal(document.getElementById('historyModal'));
    modal.show();
}

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    if (e.ctrlKey && e.key === 'Enter') {
        searchImages();
    }
    if (e.key === 'Escape') {
        clearSelection();
    }
});
